from datetime import date

from rest_framework import serializers
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import GoodsCategory, GoodsVisitCount
from meiduo_admin.serializers.users import GoodsDaySerializer
from users.models import User


class UserTotalCountView(APIView):

    # 添加权限
    permission_classes = [IsAdminUser]

    def get(self,request):

        now_date = date.today()

        count = User.objects.all().count()

        return Response({
            "count":count,

             'date':now_date
        })

class UserDailyActiveCountView(APIView):

    permission_classes = [IsAdminUser]

    def get(self,request):
        # 获取当前日期
        now_date = date.today()

        # last_login__gte=now_date  会进行比对date
        count = User.objects.filter(last_login__gte=now_date).count()
        return Response({
            'count': count,
            'date': now_date
        })

class UserDailyOrderCountView(APIView):

    permission_classes = [IsAdminUser]

    def get(self,request):
        # 获取当前日期
        now_date = date.today()
        # 获取当日下单用户数量  orders__create_time 订单创建时间>=今天
        count = User.objects.filter(orderinfo__create_time__gte=now_date).count()
        return Response({
            "count": count,
            "date": now_date
        })

from datetime import timedelta
class UserMonthCountView(APIView):

    permission_classes = [IsAdminUser]

    def get(self,request):
        # 获取当前日期
        now_date = date.today()
        # 获取一个月前日期
        start_date = now_date - timedelta(days=30)
        # 创建空列表保存每天的用户量
        date_list = []

        for i in range(31):
            # 循环遍历获取当天日期
            index_date = start_date + timedelta(days=i)
            # 指定下一天日期
            cur_date = start_date + timedelta(days=i + 1)

            # 查询条件是大于当前日期index_date，小于明天日期的用户cur_date，得到当天用户量
            count = User.objects.filter(date_joined__gte=index_date, date_joined__lt=cur_date).count()

            date_list.append({
                'count': count,
                'date': index_date
            })

        return Response(date_list)

class UserDayCountView(APIView):

    permission_classes = [IsAdminUser]

    def get(self,request):

        today_date = date.today()

        m_date = today_date + timedelta(days=1)

        count = User.objects.filter(date_joined__gt=today_date).count()

        return Response({'date':today_date,
                         'count':count})


# 实现日分类商品访问量
class GoodsDayView(APIView):
    def get(self,request):
        today_date = date.today()
        data = GoodsVisitCount.objects.filter(date__gte=today_date)
        serializer = GoodsDaySerializer(data,many=True)

        # categories = GoodsCategory.objects.all()
        # count = GoodsCategory.objects.filter().count()
        return Response(serializer.data)